<template>
  <base-breadcrumb class="ModelList-container">
    <searchData
      v-show="!visible.detail"
      :search-data="searchOptions"
      @search="handleSearch"
    />
    <a-button
      v-show="visible.detail"
      class="base-btn back-btn"
      @click="handleBack"
    >
      返回列表
    </a-button>
    <a-card
      v-show="!visible.detail"
      :bordered="false"
    >
      <div class="table-operateors mb20">
        <a-button
          type="primary"
          @click="handleChangeProject"
        >
          切换项目
        </a-button>
        <a-button
          type="primary"
          class="ml12"
          @click="handleUpdate('add')"
        >
          上传模型
        </a-button>
        <a-popover placement="top">
          <template slot="content">
            <div>
              <a href="/static/resource/RevitSetup.exe" target="_parent">RevitSetup.exe</a>
            </div>
            <div>
              <a href="/static/resource/NwDemoAddin.exe" target="_parent">NwDemoAddin.exe</a>
            </div>
          </template>
          <a-button type="primary" class="ml12" icon="paper-clip"> 下载插件 </a-button>
        </a-popover>
      </div>
      <s-table
        ref="table"
        size="default"
        row-key="id"
        :columns="columns"
        :data="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        show-pagination="auto"
        :scroll="{ y: 600 }"
      >
        <!-- :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }" -->
        <template
          slot="modelName"
          slot-scope="text, record"
        >
          <a
            href="javascript:void 0;"
            @click.stop="handleUpdate('look', record)"
          >{{ record.modelName }}</a>
        </template>
        <span
          slot="main"
          slot-scope="main"
        >
          {{ main ? '是' : '否' }}
        </span>
        <template
          slot="operator"
          slot-scope="text, record"
        >
          <a
            class="base-btn"
            @click.stop="handleUpdate('look', record)"
          >查看</a>
          <a-divider type="vertical" />
          <a
            class="base-btn"
            @click.stop="handleUpdate('edit', record)"
          >更新</a>
          <a-divider type="vertical" />
          <a
            class="base-btn"
            @click.stop="handleUpdate('delete', record)"
          >删除</a>
          <a-divider type="vertical" />
          <a
            class="base-btn"
            @click.stop="handleUpdate('download', record)"
          >下载</a>
        </template>
      </s-table>
    </a-card>
    <model-detail
      v-if="visible.detail"
      :model-id="childInitData.modelId"
      :modelList="selectedRows"
      @refresh="handleRefresh"
    />
    <upload-model
      v-if="visible.uploadModel"
      :is-edit="uploadType === 'edit'"
      :init-data="childInitData"
      @cancel="visible.uploadModel = false"
      @confirm="handleUpdateConfirm"
    />
    <SelectProjectInBim
      :visible="visible.selectProject"
      @confirm="confirmSelectProject"
      @cancel="visible.selectProject = false"
      @empty="visible.selectProject = true"
    />
  </base-breadcrumb>
</template>

<script>
import SelectProjectInBim from '@/components/BimIntegrate/SelectProjectInBim'
import { getTypeLabel } from '@/api/commons'
import { STable } from '@/components'
import UploadModel from './components/UploadModel.vue'
import { getModelList, deleteModel, downloadModel } from '@/api/bimIntegrate'
import { getBindList, deleteBind } from '@/api/bimIntegrate/business.js'
import ModelDetail from './index.vue'
import '@/utils/filter.js'

const searchOptions = [
  {
    name: '模型分类',
    value: 'cateId',
    type: 'select',
    data: []
  }
]

const columns = [
  {
    title: '模型名称',
    dataIndex: 'modelName',
    key: 'modelName',
    scopedSlots: { customRender: 'modelName' }
  },
  {
    title: '分类',
    dataIndex: 'modelCate.name',
    key: 'modelCate.name'
  },
  {
    title: '是否为主模型',
    dataIndex: 'main',
    scopedSlots: { customRender: 'main' }
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    key: 'projectName'
  },
  {
    title: '操作',
    dataIndex: 'operator',
    scopedSlots: { customRender: 'operator' }
  }
]

export default {
  components: {
    ModelDetail,
    UploadModel,
    STable,
    SelectProjectInBim
  },
  data() {
    return {
      selectedRowKeys: [],
      selectedRows: [],
      uploadType: 'add',
      searchOptions: searchOptions,
      childInitData: {},
      visible: {
        detail: false,
        uploadModel: false,
        selectProject: false
      },
      dataList: [],
      columns: columns,
      queryParam: {},
      loadData: async (parameter) => {
        const projectId = this.$store.getters['bimInfo/GET_PROJECTID']
        if (!projectId) {
          return new Promise((resolve) => {
            resolve({
              data: [],
              currentPage: 0,
              totalSize: 0
            })
          })
        }
        const requestParameters = Object.assign({}, parameter, this.queryParam, { businessId: projectId })
        const [err, res] = await getBindList(requestParameters)
        const list = res.data || []
        const mainModel = list.find((item) => item.main)
        sessionStorage.setItem('mainModel', (mainModel && mainModel.modelId) || '') // 存储主模型
        return new Promise((resolve, reject) => {
          if (err) {
            reject(err)
          } else {
            resolve(res)
          }
        })
      }
    }
  },
  computed: {
    hasProjectId() {
      return !!this.$store.getters['bimInfo/GET_PROJECTID']
    }
  },
  created() {
    this.getModelTypeList()
  },
  methods: {
    onSelectChange(keys, rows) {
      this.selectedRowKeys = keys
      this.selectedRows = rows.map(item => {
        return {
          modelId: item.modelId,
          version: 1,
        }
      })
    },
    handleChangeProject() {
      this.visible.selectProject = true
    },
    confirmSelectProject() {
      this.visible.selectProject = false
      this.handleSearch()
    },
    getModelTypeList() {
      getTypeLabel({ type: 4 }).then((res) => {
        const modelTypeList = res.data || []
        this.searchOptions.forEach((item) => {
          if (item.value === 'cateId') {
            item.data = modelTypeList.map((typeItem) => {
              return {
                label: typeItem.name,
                value: typeItem.id
              }
            })
          }
        })
      })
    },
    handleUpdateConfirm() {
      this.visible.uploadModel = false
      this.handleSearch()
    },
    handleSearch(val = {}) {
      if (!this.hasProjectId) {
        this.handleChangeProject()
        return
      }
      this.queryParam = {
        ...val
      }
      this.$refs.table.refresh(true)
    },
    deleteModel() {
      this.$confirm({
        title: '提示',
        content: '确认删除该模型？',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: async () => {
          const [err, res] = await deleteModel({
            modelId: this.childInitData.modelId
          })
          if (!err) {
            const [delBindErr, delBindRes] = await deleteBind({
              id: this.childInitData.id
            })
            if (!delBindErr) {
              this.$message.success('删除成功')
              this.handleSearch() // 刷新列表
            }
          }
        }
      })
    },
    /**
     * 封装各类操作
     */
    handleUpdate(type, data = {}) {
      this.uploadType = type
      this.childInitData = { ...data }
      const commonHandler = () => {
        if (!this.hasProjectId) {
          this.$message.error('请先选择项目，再进行相关操作')
          return
        }
        this.visible.uploadModel = true
      }
      const actionMap = {
        add: () => {
          commonHandler()
        },
        delete: () => {
          this.deleteModel()
        },
        look: () => {
          this.$router.push({
            path: '/bimIntegrate/model/modelPreview',
            query: {
              modelList: JSON.stringify([{
                modelId: data.modelId,
                version: 1
              }])
            }
          })
          // this.childInitData = {
          //   modelId: data.modelId,
          //   version: 1
          // }
          // this.visible.detail = true
        },
        edit: () => {
          commonHandler()
        },
        download: () => {
          this.handleDownload()
        }
      }
      actionMap[type] && actionMap[type]()
    },
    /**
     * 下载模型
     */
    async handleDownload() {
      const [err, res] = await downloadModel({ modelId: this.childInitData.modelId })
      if (!err) {
        const blob = new Blob([res.data])
        const filename = res.headers['content-disposition']
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = filename.substring(filename.indexOf("''") + 2) // 获取文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        window.URL.revokeObjectURL(href) //释放blob对象
      }
    },
    handleRefresh() {
      this.visible.detail = false
      this.$nextTick(() => {
        this.visible.detail = true
      })
    },
    handleBack() {
      this.visible.detail = false
    },
    async getModelList() {
      const params = {}
      const [err, res] = await getModelList(params)
      if (!err) {
        this.dataList = res.data || []
      } else {
        this.dataList = []
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ModelList-container {
  margin-top: 12px;
  position: relative;
  padding: 0 12px;
  .back-btn {
    position: absolute;
    top: 55px;
    left: 12px;
    z-index: 90;
  }
}
</style>